package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.ICourseService;
import com.xmy.cultivate.service.IOrderDetailService;
import com.xmy.cultivate.service.IQuarterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 每年季度 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-08-22
 */
@Service
public class QuarterServiceImpl extends ServiceImpl<QuarterMapper, Quarter> implements IQuarterService {

    @Autowired
    @Lazy
    QuarterMapper quarterMapper;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    IOrderDetailService iOrderDetailService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    IdWorker idWorker;

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    @Lazy
    GradeMapper gradeMapper;

    @Autowired
    @Lazy
    CompanyMapper companyMapper;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    RenewDataMapper renewDataMapper;


    public List<Map<String,Object>> getYearPartList(){
        return quarterMapper.getYearPartList();
    }

    public IPage<Map<String,Object>> findAll(IPage<?> page, Wrapper wrapper){
        return quarterMapper.findAll(page,wrapper);
    }

    public boolean saveTo(Quarter quarter){

        List<Quarter> quarterList = new ArrayList<>();
        List<Quarter> upQuarterList = new ArrayList<>();

        Iterator<Quarter> quarterIterator = quarter.getQuarterList().iterator();
        while (quarterIterator.hasNext()){
            Quarter quarter1 = quarterIterator.next();
            if(quarter1.getId()!=null && quarter1.getId() !=0){
                //添加
                quarterList.add(quarter1);
            }else {
                upQuarterList.add(quarter1);
            }
        }
        if(quarterList.size()>0){
            this.saveBatch(quarterList);
        }

        if(upQuarterList.size()>0){
            this.updateBatchById(upQuarterList,upQuarterList.size());
        }

        return true;
    }

    /**
     * 获取一条数据（暂时不使用）
     * @param yearPart
     * @param num
     * @return
     */
    public Quarter getOneForNum(String yearPart,Integer num){
        QueryWrapper<Quarter> queryWrapper =  new QueryWrapper<>();
        queryWrapper.eq("year_part",yearPart);
        queryWrapper.eq("num",num);
        Quarter quarter = quarterMapper.selectOne(queryWrapper);

        Integer year_part = quarterMapper.getMaxYearPart();

        //获取这一年的季度
        QueryWrapper<Quarter> queryWrapper1 =  new QueryWrapper<>();
        queryWrapper1.eq("year_part",year_part);
        List<Quarter> quarterList1 = quarterMapper.selectList(queryWrapper1);

        List<Quarter> quarterList = new ArrayList<>();
        Iterator<Quarter> quarterIterator = quarterList1.iterator();

        Integer yearPartNext = year_part + 1;
        while (quarterIterator.hasNext()){
            Quarter quarter1 = quarterIterator.next();
            Quarter quarter2 = new Quarter();
            quarter2.setId(idWorker.nextId());
            quarter2.setName(quarter1.getName());
            quarter2.setStartDate(quarter2.getStartDate());
            quarter2.setEndDate(quarter2.getEndDate());
            quarter2.setTwoCourseDate(quarter2.getTwoCourseDate());
            quarter2.setYearPart(yearPartNext);
            quarter2.setCreatedAt(DateUtil.getNowDateTime());
            quarterList.add(quarter2);
            if(quarter1.getNum() == num){
                quarter = quarter2;
            }
        }
        if(quarterList.size()>0){
            this.saveBatch(quarterList);
        }
        return quarter;
    }

    /**
     * 根据季度获取年份
     * @param newNum
     * @return
     */
    public Integer getQuarterYearPartForNum(Integer newNum){
        LocalDate nowDate = DateUtil.getNowDate();
        //指定日期
        Company company = companyMapper.selectById(1L);
        if(company.getIsUseEnrollYear() == 1){
            nowDate = company.getEnrollYear();
        }


        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("start_date",nowDate).ge("end_date",nowDate);

        //获取当前时间所属的季度
        Quarter quarterNow = quarterMapper.selectOne(queryWrapper);
        if(quarterNow == null){
            //季度不存在，请先添加季度
            throw new CommonException(ResultCode.quarterNo);
        }
        Integer nowQuarterNum = quarterNow.getNum();

        //通过当前的季度，获取报读的年份
        //获取当前报读的年份
        //Integer nowYeartPart = nowDate.getYear();
        Integer nowYeartPart = quarterNow.getYearPart();
        Integer newYeartPart = nowYeartPart;

        //nowQuarterNum:当前时间所属的季度，newNum：报读的季度
        if(nowQuarterNum > newNum){
            //属于下一年的季度
            newYeartPart = nowYeartPart + 1;
        }
        return newYeartPart;
    }


    /**
     * Long schoolId,Long studentId,Long subjectId,Integer quarterNum
     * @param schoolId
     * @param studentId
     * @param subjectId
     * @param quarterNum
     * @return
     * @throws ParseException
     */
    public RenewClass getRenewForPay(Long schoolId,Long studentId,Long subjectId,Integer quarterNum) throws ParseException {

        RenewClass renewClass = new RenewClass();

        Integer year_part = iQuarterService.getQuarterYearPartForNum(quarterNum);//获取报读的年份
        //System.out.print("year_part:"+year_part);


        QueryWrapper<RenewData> renewDataQueryWrapper = new QueryWrapper<>();
        renewDataQueryWrapper.eq("school_id",schoolId);
        renewDataQueryWrapper.eq("subjects_id",subjectId);
        renewDataQueryWrapper.eq("student_id",studentId);
        renewDataQueryWrapper.eq("year_part_renew",year_part);
        renewDataQueryWrapper.eq("quarter_num_renew",quarterNum);
        renewDataQueryWrapper.eq("type",1);
        RenewData renewData = renewDataMapper.selectOne(renewDataQueryWrapper);

        String rsStr = "";

        //为空表示没有需要续班的信息
        if(renewData != null){
            //还没有续班成功
            if(renewData.getIsRenew()!=1){
                String quarterName = ConfigData.getQuarterForNum(renewData.getQuarterNum());
                String quarterNameRenew = ConfigData.getQuarterForNum(renewData.getQuarterNumRenew());
                rsStr = quarterName+"续"+quarterNameRenew;
            }
            renewClass.setYearPart(year_part);
            renewClass.setRenewType(1);
            renewClass.setTypeName(rsStr);
        }else{
            QueryWrapper<RenewData> renewDataQueryWrapperNext = new QueryWrapper<>();
            renewDataQueryWrapperNext.eq("school_id",schoolId);
            renewDataQueryWrapperNext.eq("subjects_id",subjectId);
            renewDataQueryWrapperNext.eq("student_id",studentId);
            renewDataQueryWrapperNext.eq("year_part_renew",year_part);
            renewDataQueryWrapperNext.eq("quarter_num_renew",quarterNum);
            renewDataQueryWrapperNext.eq("type",2);
            RenewData renewDataNext = renewDataMapper.selectOne(renewDataQueryWrapperNext);

            if(renewDataNext!=null){
                if(renewDataNext.getIsRenew() != 1){
                    String quarterName = ConfigData.getQuarterForNum(renewDataNext.getQuarterNum());
                    String quarterNameRenew = ConfigData.getQuarterForNum(renewDataNext.getQuarterNum());
                    rsStr = quarterName+"续"+quarterNameRenew;
                }
                renewClass.setRenewType(1);
                renewClass.setTypeName(rsStr);
            }else{
                String quarterName = ConfigData.getQuarterForNum(quarterNum);
                renewClass.setYearPart(year_part);
                renewClass.setRenewType(0);
                renewClass.setTypeName(quarterName);
                renewClass.setQuarterName(quarterName);
            }
        }

        return renewClass;
    }

    /**
     * 获取转课信息
     * @param studentId
     * @param schoolId
     * @param subjectId
     * @param courseId
     * @param houseNum
     * @return
     */
    public RenewClass getRenewForTransfer(Long studentId,Long schoolId,Long subjectId,Long courseId,Integer houseNum,Integer lessonType){
        Map<String,String> map = new HashMap<>();

        //获取报读课程
        Course course = iCourseService.getById(courseId);

        //新报读的季度
        Integer newNum = course.getQuarterNum();

        LocalDate nowDate = DateUtil.getNowDate();
        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("start_date",nowDate).ge("end_date",nowDate);

        //获取当前时间所属的季度
        Quarter quarterNow = quarterMapper.selectOne(queryWrapper);
        if(quarterNow == null){
            //季度不存在，请先添加季度
        }
        Integer nowQuarterNum = quarterNow.getNum();

        //通过当前的季度，获取报读的年份
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Integer nowYeartPart = Integer.valueOf(sdf.format(nowDate));

        //获取当前报读的年份
        Integer newYeartPart = nowYeartPart;
        if(nowQuarterNum > newNum){
            newYeartPart = nowYeartPart + 1;
        }

        //报读季度的信息
        QueryWrapper<Quarter> newQueryWrapper = new QueryWrapper<>();
        newQueryWrapper.eq("year_part",newYeartPart).ge("num",newNum);
        //获取当前报读所属的季度信息
        Quarter newQuarter = quarterMapper.selectOne(newQueryWrapper);

        RenewClass renewClass = new RenewClass();
        renewClass.setSchoolId(schoolId);
        renewClass.setStudentId(studentId);
        renewClass.setCourseId(courseId);
        renewClass.setQuarterNum(newNum);
        renewClass.setYearPart(newYeartPart);
        renewClass.setType(newNum);//续班类型：2春续暑，3暑续秋，4秋续寒，1寒续春
        String[] typeNameArr = {"无","寒续春","春续暑","暑续秋","秋续寒"};
        renewClass.setTypeName(typeNameArr[newNum]);
        renewClass.setReSetIsnew(0);

        Integer diffNum = 0;

        //是否报读过
        Integer count = iOrderDetailService.getApplyCountForSubjects(schoolId,studentId,subjectId,newYeartPart,newNum,lessonType);

        if(count == 0){
            //没有报读过，属于新生
            renewClass.setStatus(0);//续班失败
            renewClass.setRemark("新报，不算续班");
            return renewClass;
        }

        //获取报读过的最后一次所在班级
        StudentGrade studentGrade = studentGradeMapper.getLastForStudent(schoolId,studentId,subjectId,newYeartPart,newNum);
        Grade grade = null;
        if (studentGrade!=null){
            grade = gradeMapper.selectById(studentGrade.getGradeId());
        }
        if(grade!=null){
            renewClass.setTeacherId(grade.getTeacherId());
        }

        //获取该课最后，当前所报季度之前的最后一期的报读信息
        Map<String,Object> oldCourseMap = orderDetailMapper.getApplyCourseForSubjects(schoolId,studentId,subjectId,newYeartPart,newNum,grade.getLessonType());



        //之前最后一期报读的年份
        Integer oldYearPart = Integer.parseInt(oldCourseMap.get("yearPart").toString());
        //之前最后一期报读的季度
        Integer oldNum = Integer.parseInt(oldCourseMap.get("quarterNum").toString());
        Integer isNewStudent = Integer.parseInt(oldCourseMap.get("isNewStudent").toString());

        Map<String,Integer> quarterMap =  new HashMap<>();
        quarterMap.put("oldYear",oldYearPart);
        quarterMap.put("oldNum",oldNum);
        quarterMap.put("newYear",newYeartPart);
        quarterMap.put("newNum",newNum);

        /**
         * 报读相差多少个季度
         */
        diffNum = CommonUtil.diffQuarter(quarterMap);
        renewClass.setDiffNum(diffNum);

        Integer yearAndQuarter = Integer.parseInt(newYeartPart +"" +course.getQuarterNum());
        //获取剩余课时
        Integer residueCourseCount = orderDetailMapper.getResidueCourseCount(schoolId,studentId,subjectId,yearAndQuarter,grade.getLessonType());
        //剩余课时加当前续班课时
        Integer allHouseNum = houseNum + residueCourseCount;
        Integer classNum = (Integer) allHouseNum / 3;//计算出课次

        if(diffNum == 0){
            //同年同季度，属于续费，不属于续班
            renewClass.setStatus(0);
            renewClass.setRemark("同年同季度，属于续费，不属于续班，续班失败");
            //return renewClass;
        }
        else if(diffNum == 1){
            //属于下一个季度

            //属于新生
            if(isNewStudent == 1){
                if(classNum>=3){
                    //续班成功
                    renewClass.setStatus(1);
                    renewClass.setRemark("属于新生,加上剩余课时为："+allHouseNum+"，大于或等于15课时，续班成功");
                    //return renewClass;
                }else{
                    //续班成功
                    renewClass.setStatus(0);
                    renewClass.setRemark("属于新生,加上剩余课时为："+allHouseNum+"，小于15课时，续班失败");
                    //return renewClass;
                }
            }else{
                if(classNum >= 15){
                    //续班成功
                    renewClass.setStatus(1);
                    renewClass.setRemark("属于老生，加上剩余课时为："+allHouseNum+"，大于或等于45课时，续班成功");
                }else {
                    //续班失败
                    renewClass.setStatus(0);
                    renewClass.setRemark("老生并且加上剩余课时为："+allHouseNum+"，小于45课时，续班失败");
                }
            }

        }
        else if(diffNum == 2){
            //属于隔一个季度
            //小于或者等于
            renewClass.setStatus(0);
            renewClass.setRemark("相隔了"+diffNum+"期，续班失败");

            //第二次课的时间是否大于或等于当前时间
            if(nowDate.isBefore(newQuarter.getTwoCourseDate()) || nowDate.isEqual(newQuarter.getTwoCourseDate())){
                //第二次课之前缴费的，计入隔季续班的人数,判断diffNum等于2就只可以
                if(classNum >= 15){
                    renewClass.setIsRenewPerson(1);
                }
            }else {
                //第二次课之后缴费的，重置为新生
                //重置些学生为新生
                renewClass.setReSetIsnew(1);
            }
        }else if(diffNum > 2){
            //属于大于2个季度以上,续班失败
            renewClass.setStatus(0);
            renewClass.setRemark("相隔了"+diffNum+"期，续班失败");
            //重置些学生为新生
            renewClass.setReSetIsnew(1);
        }else {
            renewClass.setStatus(0);
            renewClass.setRemark("相隔了"+diffNum+"期，续班失败");
            //重置些学生为新生
            renewClass.setReSetIsnew(1);
        }
        return renewClass;
    }

    public Quarter getNowQuarter(){
        LocalDate nowDate = LocalDate.now();
        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("start_date",nowDate);
        queryWrapper.ge("end_date",nowDate);
        queryWrapper.last("limit 1");
        Quarter quarter = iQuarterService.getOne(queryWrapper);
        return quarter;
    }

    public Quarter getQuarterByDate(LocalDate date){
        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("start_date",date);
        queryWrapper.ge("end_date",date);
        queryWrapper.last("limit 1");
        Quarter quarter = iQuarterService.getOne(queryWrapper);
        return quarter;
    }


    /**
     * 获取上一个季度
     * @return
     */
    public Quarter getLastQuarter(Integer yearPart,Integer quarterNum){
            return quarterMapper.getLastQuarter(yearPart,quarterNum);
    }

    /**
     * 获取上一个学期(非假期的上一个学期)，成绩填写
     * @param yearPart
     * @param quarterNum
     * @return
     */
    @Override
    public Quarter getLastForTranscription(Integer yearPart, Integer quarterNum){
        Quarter quarter = this.getLastQuarter(yearPart,quarterNum);
        if (quarter!=null){
            if (quarter.getType().equals(2)){
                quarter = this.getLastQuarter(quarter.getYearPart(),quarter.getNum());
            }
        }
        return quarter;
    }

    @Override
    public Quarter getQuarterForYearAndNum(Integer yearPart, Integer num) {
        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("year_part",yearPart);
        queryWrapper.eq("num",num);
        queryWrapper.last("limit 1");
        Quarter quarter = quarterMapper.selectOne(queryWrapper);
        return quarter;
    }

    @Override
    public List<Quarter> getQuarterBigIdList(Long id){
        return quarterMapper.getQuarterBigIdList(id);
    }

    /**
     * 根据年份与学期获取一条数据
     * @param yearPart
     * @param quarterNum
     * @return
     */
    @Override
    public Quarter getOneForYearAndNum(Integer yearPart,Integer quarterNum){
        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("year_part",yearPart);
        queryWrapper.eq("num",quarterNum);
        queryWrapper.last("limit 1");
        Quarter quarter = this.getOne(queryWrapper);
        return quarter;
    }

    /**
     * 获取结束id最大的一条数据
     * @param endId
     * @return
     */
    @Override
    public Quarter getQuarterMaxForId(Integer endId){
        return quarterMapper.getQuarterMaxForId(endId);
    }

    @Override
    public Integer getIdForYearPartAndNum(Integer yearPart,Integer quarterNum){
        return quarterMapper.getIdForYearPartAndNum(yearPart,quarterNum);
    }

    /**
     * 获取前面第几个学期
     * @param yearPart
     * @param quarterNum
     * @param upNum
     * @return
     */
    @Override
    public Quarter getUpQuarter(Integer yearPart, Integer quarterNum, Integer upNum){
        Quarter quarter = this.getOneForYearAndNum(yearPart,quarterNum);
        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        Integer upNumId = Integer.parseInt(quarter.getId().toString()) - upNum;
        if (upNumId<1){
            upNumId = 1;
        }
        queryWrapper.eq("id",upNumId);
        Quarter upQuarter = this.getOne(queryWrapper);
        upQuarter.setAliasName(upQuarter.getName());
        //upQuarter.setSort(upNum);
        return upQuarter;

    }
}
